import Taro from "@tarojs/taro";
import { useEffect } from "react";
import { DeviceProvider } from "@/store/deviceContext";
import { AuthProvider } from "@/store/authContext";
import { ApplicationProvider } from "@/store/applicationDataContext";
import { UserInfoProvider } from "@/store/userDataContext";
import "./hxt/hxt";
import "./app.scss";

function App({ children }) {
  //tracking
  useEffect(() => {
    Taro.login({
      success(res: any) {
        if (res.code) {
          Taro.request({
            url: `${process.env.apiEndpoint}/wechat/authorize/program/login?code=${res.code}`,
            method: "POST",
            data: {},
            success: function (e: any) {

              const { data } = e;
              if (data.data && data.data.type) {
                const { openID, unionID, token } = data.data;
                const identifyElements = unionID
                  ? { openid: openID, unionid: unionID }
                  : { openid: openID };
                Taro.getApp().hxt.identify(identifyElements);
                Taro.setStorageSync("token", token);
              }
            },
          });
        }
      },
    });
  }, []);

  return (
    <DeviceProvider>
      <AuthProvider>
        <ApplicationProvider>
          <UserInfoProvider>{children}</UserInfoProvider>
        </ApplicationProvider>
      </AuthProvider>
    </DeviceProvider>
  );
}

export default App;
